package com.situ.meetingRoom.dao.impl;

import com.situ.meetingRoom.dao.DeptDao;
import com.situ.meetingRoom.entity.Dept;
import com.situ.meetingRoom.util.DBUtil;
import com.situ.meetingRoom.util.PageInfo;
import com.situ.meetingRoom.vo.UserVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DeptDaoImpl implements DeptDao {
    private DBUtil dbUtil = new DBUtil();
    @Override
    public List<Dept> selectAll(Dept dept) {
        String sql = "select * from dept where 1=1 ";
        List<Object> params = new ArrayList<>();
        if (dept.getName() != null && dept.getName().length() > 0) {
            sql += "and name like ? ";
            params.add("%" + dept.getName() + "%");
        }
        if (dept.getStatus() != null) {
            sql += "and status = ? ";
            params.add(dept.getStatus());
        }
        return dbUtil.query(Dept.class, sql, params.toArray());

    }

    @Override
    public PageInfo selectForPage(Integer page, Integer limit, Dept dept) {
        String sqlWhere = "";
        List<Object> params = new ArrayList<>();

        if (dept.getName() != null && dept.getName().length() > 0) {
            sqlWhere += "and name like ? ";
            params.add("%" + dept.getName() + "%");
        }
        if (dept.getStatus() != null) {
            sqlWhere += "and status = ? ";
            params.add(dept.getStatus());
        }

        //记录的条数
        String sql = "select count(*) count from dept where 1=1 " + sqlWhere;
        List<Map<String, Object>> list1 = dbUtil.query(sql, params.toArray());
        Long count = (Long) list1.get(0).get("count");


        sql = "select * from dept where 1=1  " + sqlWhere +
                " limit ?,? ";

        params.add((page - 1) * limit);
        params.add(limit);

        List list = dbUtil.query(sql, params.toArray());

        PageInfo pageInfo = new PageInfo(count, list);

        return pageInfo;
    }


    @Override
    public int insert(Dept dept) {
        String sql = "insert into dept (name) values (?)";
        return dbUtil.update(sql,dept.getName());
    }

    @Override
    public Dept selectById(Integer id) {
        String sql = "select * from dept where id=?";
        return dbUtil.queryOne(Dept.class, sql, id);
    }

    @Override
    public int update(Dept dept) {
        String sql = "update dept " +
                "set ";
        List<Object> params = new ArrayList<>();
        if (dept.getName() != null && dept.getName().length() > 0) {
            sql += "name=?,";
            params.add(dept.getName());
        }
        if (dept.getStatus() != null) {
            sql += "status=?,";
            params.add(dept.getStatus());
        }
        sql = sql.substring(0, sql.length() - 1);
        sql += " where id = ?";
        params.add(dept.getId());
        return dbUtil.update(sql, params.toArray());
    }


}
